from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.images import ImageSerializer, SKUSerializer
from apps.meiduo_admin.utils import PageNum


class ImageAPIView(ModelViewSet):
    # 查询结果集
    queryset = SKUImage.objects.all()
    # 设置序列化器
    serializer_class = ImageSerializer
    # 设置分页类
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        # 接收数据
        data=request.data
        # 验证数据
        sku_id=data.get('sku')
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response({'msg': '商品查询失败'})
        # Fdfs图片保存
        from fdfs_client.client import Fdfs_client
        #     加载Fdfs的配置文件,来设置Tracker Server.
        client=Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        # 获取上传的图片对象
        image=data.get('image')
        # 读取二进制  read() 方法是读取图片的二进制数据
        image_data=image.read()
        # 上传图片
        result = client.upload_by_buffer(image_data)
        #     根据结果进行判断

        if result.get('Status') != 'Upload successed.':
            return Response({'msg':'请稍后再试'})
        file_id=result.get('Remote file_id')

        # 将数据存入数据库
        new_image=SKUImage.objects.create(
            sku=sku,
            image=file_id
        )
        # 返回响应
        # 响应状态码 必须是 201
        return Response({
            "id": new_image.id,
            "sku": sku_id,
            "image": file_id
        },status=201)


    def update(self, request, *args, **kwargs):
        # 获取更新的对象
        old_image = self.get_object()
        # 接收验证数据
        image = request.data.get('image')
        image_data = image.read()
        # 通过Fdfs保存图片
        client=Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        if result['Status'] != 'Upload successed.':
            return Response({'msg':'上传失败'})
        file_id = result.get('Remote file_id')
        # 更新数据
        old_image.image = file_id
        old_image.save()
        # 返回
        return Response({
            "id": old_image.id,
            "image": file_id,
            'sku': request.data.get('sku')
        },status=201)


# 获取sku列表数据
class SKUListView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer